package com.kuanter.kuanterauto.utils;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.kuanter.kuanterauto.entity.MapResult;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.net.QHttpClientUtils;
/**
 * 异步请求数据
 * @author soup
 *
 */
public class DataLoader {

	// 线程池
	private ExecutorService executorService;
	MapResult mapR = null;
	private DatasLoader dataLoader = null;
	private Context context = null;

	// HttpClient client;

	public DataLoader(Context context) {
		mapR = MapResult.getMapResults();
		executorService = Executors.newFixedThreadPool(5);
		this.context = context;
		// client = QHttpClientUtils.getHttpClient(context);
	}

	public void DisplayData(String url, List<NameValuePair> params,
			Handler handler, String id, boolean isc) {
		if (!id.equals("")) {
			String str = mapR.getValueForKey(id);
			if (str != null) {
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putString("result", str);
				msg.what = HttpTask.RESULT_OK;
				msg.setData(bundle);
				handler.sendMessage(msg);
				System.out.println("memoryCache");
			} else {
				System.out.println("not memoryCache");
				dataLoader = new DatasLoader(url, params, handler, id, isc);
				executorService.submit(dataLoader);
			}
		} else {
			dataLoader = new DatasLoader(url, params, handler, id, isc);
			executorService.submit(dataLoader);
		}

	}

	// public void shutDown(){
	// if(client!=null){
	// client.getConnectionManager().shutdown();
	// }
	// }

	class DatasLoader implements Runnable {

		List<NameValuePair> params;
		Handler handler;
		String url;
		String id;
		int l_num = 0;
		HttpClient client;
		boolean isc = false;

		public DatasLoader(String url, List<NameValuePair> params,
				Handler handler, String id, boolean isc) {
			this.params = params;
			this.handler = handler;
			this.url = url;
			this.id = id;
			client = QHttpClientUtils.getHttpClient(context);
			this.isc = isc;
		}

		@Override
		public void run() {
			String result = "";
			// HttpClient client = QHttpClientUtils.getHttpClient(
			// HttpTask.proxyHost, HttpTask.proxyPort);
			HttpPost post = new HttpPost(url);
			HttpResponse respons = null;

			try {
				if (params != null) {
					UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
							params, HTTP.UTF_8);
					post.setEntity(entity);
				}

				client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);	//连接超时
				client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);   //读取超时
				respons = client.execute(post);

				if (respons.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					result = EntityUtils.toString(respons.getEntity(),HTTP.UTF_8);
					// response.
				} else {
					result = "网络连接错误";
				}
				Log.i("aaa", "ok");
			} catch (Exception e) {
				if (isc) {
					System.out.println(isc);
					try {
						respons = client.execute(post);
					} catch (Exception e1) {
						result = "网络连接错误";
						post.abort();
						e1.printStackTrace();
					} finally {
						client.getConnectionManager().shutdown();
					}
				} else {
					System.out.println("result");
					post.abort();
					result = "网络连接错误";
					e.printStackTrace();
				}
			} finally {
				if (!isc) {
					client.getConnectionManager().shutdown();
				}
			}

			Message msg = new Message();
//			Bundle bundle = new Bundle();
			if (result.equals("网络连接错误")) {
				msg.what = HttpTask.RESULT_ERROR;
				handler.sendMessage(msg);
			} else {
				if (!id.equals("")) {
					mapR.putValueForKey(id, result);
				}
//				bundle.putString("result", result);
				msg.what = HttpTask.RESULT_OK;
//				msg.setData(bundle);
				msg.obj = result;
				handler.sendMessage(msg);

			}
		}

	}

}
